﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.IO;
using common;

namespace DES
{
    public class DESCoder : IDEncrypt
    {
        /// <summary>
        /// DES加解密算法支持64为编码，本例子用Unicode编码，一个英文或中文字符都是2个字节，一个字节8位，刚好64位
        /// 这里如果定义密钥长度不是4的字符串就会发生异常
        /// </summary>
        static string encryptKey = "1234";///////定义密钥
        public DESCoder(string key)
        {
            encryptKey = key;
        }
        public string Encrypt(string str)
        {
            byte[] key = Encoding.Unicode.GetBytes(encryptKey);//把字符串的密钥用Unicode转换成字节数组
            byte[] data = Encoding.Unicode.GetBytes(str);//把需要加密的字符串用Unicode转换成字节数组

            DESCryptoServiceProvider descrypt = new DESCryptoServiceProvider();//初始化一个加解密类实例

            MemoryStream memStream = new MemoryStream();//初始化一个内存流
            //用内存流来初始化一个加解密流
            CryptoStream cryptStream = new CryptoStream(memStream, descrypt.CreateEncryptor(key, key), CryptoStreamMode.Write);
            cryptStream.Write(data, 0, data.Length);//向加密流写入数据
            cryptStream.FlushFinalBlock();// 将加密流写入内存流

            return Convert.ToBase64String(memStream.ToArray());//先把内存流写入字节数组，在把8位无符号整数的字节数组转换为
            //与其等同的字符串
        }

        public string Decrypt(string str)
        {
            byte[] key = Encoding.Unicode.GetBytes(encryptKey);//把字符串的密钥用Unicode转换成字节数组
            byte[] data = Convert.FromBase64String(str); //二进制编码成的64为字符串，转回8位无符号整数的字节数组

            DESCryptoServiceProvider descrypt = new DESCryptoServiceProvider();
            MemoryStream memStream = new MemoryStream();
            CryptoStream cryptStream = new CryptoStream(memStream, descrypt.CreateDecryptor(key, key), CryptoStreamMode.Write);
            cryptStream.Write(data, 0, data.Length);
            cryptStream.FlushFinalBlock();

            return Encoding.Unicode.GetString(memStream.ToArray());//把字节数组用Unicode编码返回字符串
        }

        
    }
}

